package com.centling.smartSealForPhone.activity;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioGroup;

import com.centling.smartSealForPhone.BuildConfig;
import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.adapter.MainTabAdapter;
import com.centling.smartSealForPhone.application.SmartSeal;
import com.centling.smartSealForPhone.bean.LoginBean;
import com.centling.smartSealForPhone.constants.GlobalData;
import com.centling.smartSealForPhone.constants.SPConstants;
import com.centling.smartSealForPhone.constants.UrlConstants;
import com.centling.smartSealForPhone.constants.UserType;
import com.centling.smartSealForPhone.event.ReceiveNotificationEvent;
import com.centling.smartSealForPhone.event.ReceiveUnreadMsgCountEvent;
import com.centling.smartSealForPhone.service.UploadImageService;
import com.centling.smartSealForPhone.utils.BlueToothScanUtil;
import com.centling.smartSealForPhone.utils.OkHttpUtil;
import com.centling.smartSealForPhone.utils.SPUtil;
import com.centling.smartSealForPhone.utils.ShowDialog;
import com.centling.smartSealForPhone.utils.ShowToast;
import com.centling.smartSealForPhone.view.MainTabsViewPager;
import com.centling.smartSealForPhone.widget.DrawableRadioButton;
import com.centling.smartSealForPhone.widget.badgeview.BGABadgeLinearLayout;
import com.google.gson.Gson;
import com.wsdk.service.BluetoothLeService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainTabsActivity extends BaseActivity {

    private static final int OPEN_BLUE_DIALOG = 1000;

    private MainTabsViewPager vpMain;

    private RadioGroup rgTabGroup;
    private List<DrawableRadioButton> radioButtonList = new ArrayList<>();
    private DrawableRadioButton rb4;
    private BGABadgeLinearLayout blll4;

    private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                if (BuildConfig.DEBUG) {
                    ShowToast.shortTime("Main Connected");
                }
                GlobalData.isConnect = true;
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                byte[] data = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
//                if (ParseBluetoothData.isGetSN(data)) {
//                    String sn = ParseBluetoothData.parseSN(data);
//                    if (sn != null) {
//                        if (sn.equals(loginBean.getEquipRegisterInfo().getSn())) {
//                            ShowToast.shortTime("连接成功");
//                        } else {
//                            ShowToast.shortTime("序列号与服务端不一致");
//                        }
//                    }
//                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EventBus.getDefault().register(this);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        registerReceiver(bluetoothReceiver, intentFilter);

        if (!BlueToothScanUtil.checkBTAvailable()) {
            ShowToast.shortTime("您的手机不支持蓝牙");
            finish();
            return;
        }
        /*
          判断网络是否为WIFI
         */
        ConnectivityManager connectMgr = (ConnectivityManager) SmartSeal.getInstance()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectMgr != null) {
            NetworkInfo info = connectMgr.getActiveNetworkInfo();

            if (info != null) {
                if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                    startService(new Intent(mContext, UploadImageService.class));
                } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
                    ShowDialog.showSelectDialog(mContext, "警告", "您当前正在使用移动网络，将会产生大量流量",
                            "推荐在WIFI下上传", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    startService(
                                            new Intent(mContext, UploadImageService.class));
                                }
                            });
                }
            }
        }

        rgTabGroup = findViewById(R.id.tabs_bottom);

        DrawableRadioButton rb0 = findViewById(R.id.tabs_guide0);
        DrawableRadioButton rb1 = findViewById(R.id.tabs_guide1);
        DrawableRadioButton rb2 = findViewById(R.id.tabs_guide2);
        DrawableRadioButton rb3 = findViewById(R.id.tabs_guide3);
        rb4 = findViewById(R.id.tabs_guide4);
        blll4 = findViewById(R.id.bl_tabs_guide4);
        radioButtonList.add(rb0);
        radioButtonList.add(rb1);
        radioButtonList.add(rb2);

        LoginBean loginBean = getIntent().getParcelableExtra("loginbean");
        if (loginBean == null) {
            loginBean = new Gson().fromJson(SPUtil.getString(SPConstants.LOGIN_JSON), LoginBean.class);
        }

        String type = SPUtil.getString(SPConstants.USER_TYPE);
        String machineType = loginBean.getEquipRegisterInfo().getEquipType();
        if (TextUtils.equals(machineType, "0")) {
            rb1.setVisibility(View.GONE);
            radioButtonList.remove(rb1);
        }
        if (TextUtils.equals(type, UserType.EQUIP_ADMIN)) {
            radioButtonList.add(rb3);
        } else if (TextUtils.equals(type, UserType.EQUIP_OPERATOR)) {
            rb3.setVisibility(View.GONE);
        } else {
            radioButtonList.remove(rb1);
            rb1.setVisibility(View.GONE);
            rb3.setVisibility(View.GONE);
        }

        initRadioButtonOnCheckedChangeListener();

        vpMain = findViewById(R.id.vp_main_container);
        vpMain.setAdapter(new MainTabAdapter(getSupportFragmentManager(), type, machineType));
        vpMain.setOffscreenPageLimit(4);

        boolean isFromLogin = getIntent().getBooleanExtra("fromLogin", false);

        macAddress = loginBean.getEquipRegisterInfo().getBlueToothMac();
        sn = SPUtil.getString(SPConstants.CORE_SN);
        if (isFromLogin && !GlobalData.isConnect && BlueToothScanUtil.isBlueToothOpened()) {
            if (TextUtils.equals(type, UserType.EQUIP_ADMIN) || TextUtils.equals(type, UserType.EQUIP_OPERATOR)) {
                blueToothScanUtil.setMacAddress(macAddress);
                blueToothScanUtil.startSearchBlueDevice();
            }
        }
    }

    private void initRadioButtonOnCheckedChangeListener() {
        rgTabGroup.check(R.id.tabs_guide0);
        for (int i = 0; i < radioButtonList.size(); i++) {
            DrawableRadioButton child = radioButtonList.get(i);
            child.setTag(i);
            child.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        rb4.setChecked(false);
                        vpMain.setCurrentItem((Integer) buttonView.getTag(), false);
                    }
                }
            });
        }
        rb4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked) {
                    rgTabGroup.clearCheck();
                    vpMain.setCurrentItem(radioButtonList.size(), false);
                    blll4.hiddenBadge();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!BlueToothScanUtil.isBlueToothOpened()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, OPEN_BLUE_DIALOG);
        }

        tryToFetchUnreadMsgCount();
    }

    private void tryToFetchUnreadMsgCount() {
        getEnqueue(UrlConstants.FETCH_UNREAD_MSG_COUNT,new OkHttpUtil.NetCallBack() {
            @Override
            public void onSucceed(String json) {
                int count = 0;
                try {
                    JSONObject result = new JSONObject(json);
                    count = result.optInt("unreadCount");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                EventBus.getDefault().post(new ReceiveNotificationEvent(count > 0));
                EventBus.getDefault().post(new ReceiveUnreadMsgCountEvent(count));
            }

            @Override
            public void onFailed(String reason) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(bluetoothReceiver);
        blueToothScanUtil.stopSearch(false);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OPEN_BLUE_DIALOG && resultCode == RESULT_OK) {
            blueToothScanUtil = new BlueToothScanUtil(mContext);
            blueToothScanUtil.setMacAddress(macAddress);
            blueToothScanUtil.startSearchBlueDevice();
        }
    }

    private long exitTime;

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            ShowToast.shortTime("再按一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            super.onBackPressed();
            AtyManager.INSTANCE.finishAllActivities();
            stopService(new Intent(mContext, BluetoothLeService.class));
        }
    }

    @Subscribe
    public void receiveNewMsg(ReceiveNotificationEvent event) {
        if (event.isNewMsg) {
            blll4.showCirclePointBadge();
        } else {
            blll4.hiddenBadge();
        }
    }
}
